/**
 * File Name   : DiscountService.java
 * Description : 
 */
package com.hh.admin.discount.service;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;

import com.hh.admin.discount.form.DiscountBean;
import com.hh.admin.discount.form.DiscountForm;
import com.hh.common.consts.ConfConst;
import com.hh.common.ibatis.dao.IQueryDao;
import com.hh.common.ibatis.dao.IUpdateDao;
import com.hh.common.util.upload.FileUploader;
import com.hh.common.util.upload.RandomFileRenamePolicy;

/**
 * 消费打折Service
 * @author 冯昌硕
 * @create 2013-3-12 下午8:12:18
 */
public class DiscountService {
    
    private static final Logger log = Logger.getLogger(DiscountService.class);
    
    /**
     * 每个文件最大5MB
     */
    private static final int MAX_POST_SIZE = 5 * 1024 * 1024;

    private IQueryDao queryDao;
    
    private IUpdateDao updateDao;
    
    /**
     * 添加消费打折记录
     * @param form
     * @return
     * @throws Exception 
     * @create 2013-3-12 下午9:35:14
     */
    public int insertDiscount(DiscountForm form) throws Exception {
        // 1. 处理图片文件
        // 通栏广告上传目录
        String fileUploadDirStr = ConfConst.WEBCONTENT_BASE_DIR + File.separator + ConfConst.UPLOAD_DISCOUNT_DIR;
        log.debug("消费打折上传目录fileUploadDirStr=[" + fileUploadDirStr + "]");
        File fileUploadDir = new File(fileUploadDirStr);
        if (!fileUploadDir.exists()) {
            fileUploadDir.mkdirs();
        }

        FormFile discountImgFile = form.getDiscountFile();
        String fileName = discountImgFile.getFileName();

        // 文件大小限定
        int fileSize = discountImgFile.getFileSize();
        if (fileSize > MAX_POST_SIZE) {
            throw new Exception(fileName + "文件大小超过限制");
        }

        // 重命名策略
        RandomFileRenamePolicy rfp = new RandomFileRenamePolicy();
        String newFileName = rfp.rename(fileName);

        // 将文件生成到服务器指定目录下
        log.debug("上传文件[" + fileName + "]到目录[" + fileUploadDirStr + "] begin");
        boolean uploaded = FileUploader.upload(fileUploadDirStr, discountImgFile, newFileName);
        log.debug("上传文件[" + fileName + "]到目录[" + fileUploadDirStr + "] end");

        if (!uploaded) {
            log.info("上传文件[" + fileName + "]到目录[" + fileUploadDirStr + "]失败");
            throw new Exception("上传文件[" + fileName + "]到目录[" + fileUploadDirStr + "]失败");
        }

        // 2. 添加记录
        DiscountBean paramBean = new DiscountBean();
        paramBean.setTitle(form.getTitle());   // 标题
        paramBean.setStatus(form.getStatus()); // 内容状态
        paramBean.setCreateUser(form.getCreateUser());
        paramBean.setSrcUrl("/discountImg/" + newFileName);  // 广告图片文件路径
        paramBean.setTitleImgDisname(fileName);              // 图片显示名称
        paramBean.setDetailContent(form.getDetailContent()); // 正文
        paramBean.setDiscountType(form.getDiscountType());   // 类型
        
        log.debug("新增消费打折信息 paramBean=[" + paramBean + "]");
        return (Integer) updateDao.insert("discount.insertDiscount", paramBean);
    }
    
    /**
     * 获取内容详情
     * @param form
     * @return
     * @throws SQLException 
     * @throws ClassCastException 
     * @create 2013-3-12 下午10:03:15
     */
    public DiscountBean getDiscountDetail(int id) throws ClassCastException, SQLException {
        return queryDao.queryForObject("discount.selDiscountDetail", id, DiscountBean.class);
    }
    
    /**
     * 更新内容记录
     * @param form
     * @return
     * @throws SQLException
     * @create 2013-3-12 下午10:20:34
     */
    public int updateDiscount(DiscountForm form) throws Exception {
        DiscountBean paramBean = new DiscountBean();
        
        // 图片文件更新操作
        // 如果有图片文件上传则更新图片文件，删除旧的图片，上传新的图片
        FormFile ff = form.getDiscountFile();
        if(ff != null && (ff.getFileName() != null) && (!"".equals(ff.getFileName()))) {
            RandomFileRenamePolicy rfrp = new RandomFileRenamePolicy();
            String newFileName = rfrp.rename(ff.getFileName());
            
            String fileUploadDirStr = ConfConst.WEBCONTENT_BASE_DIR + File.separator + ConfConst.UPLOAD_DISCOUNT_DIR;
            log.debug("消费打折标题图片上传目录fileUploadDirStr=[" + fileUploadDirStr + "]");
            File fileUploadDir = new File(fileUploadDirStr);
            if (!fileUploadDir.exists()) {
                fileUploadDir.mkdirs();
            }

            String fileName = ff.getFileName();

            // 文件大小限定
            int fileSize = ff.getFileSize();
            if (fileSize > MAX_POST_SIZE) {
                throw new Exception(fileName + "文件大小超过限制");
            }
            
            boolean uploadRs = FileUploader.upload(fileUploadDirStr, ff, newFileName);
            if(!uploadRs) {
                throw new Exception(fileName + "上传失败");
            }
            
            DiscountBean oldRecord = this.getDiscountDetail(form.getId());
            
            // 删除旧的文件
            String delFilePath = ConfConst.WEBCONTENT_BASE_DIR + File.separator + "resource" 
                    + File.separator + "uploadimg" + File.separator + oldRecord.getSrcUrl();
            FileUploader.delete(delFilePath);
            
            // TODO 删除旧正文里的图片文件
            
            paramBean.setTitleImgDisname(ff.getFileName());     // 图片显示名称
            paramBean.setSrcUrl("/discountImg/" + newFileName); // 广告图片文件路径
        }
        
        //
        paramBean.setId(form.getId());
        paramBean.setTitle(form.getTitle());   // 标题
        paramBean.setStatus(form.getStatus()); // 内容状态
        paramBean.setCreateUser(form.getCreateUser());
        paramBean.setDetailContent(form.getDetailContent()); // 正文
        paramBean.setDiscountType(form.getDiscountType());   // 类型
        
        log.debug("更新消费打折信息  paramBean=[" + paramBean + "]");
        return updateDao.update("discount.updateDiscount", paramBean);
    }
    
    /**
     * 删除单条记录
     * @param id
     * @return
     * @throws SQLException 
     * @throws ClassCastException 
     * @create 2013-3-12 下午10:44:21
     */
    public int deleteOneDiscount(int id) throws Exception {
        // 删除图片
        DiscountBean oldRecord = this.getDiscountDetail(id);
        String filePath = oldRecord.getSrcUrl();
        String delFilePath = ConfConst.WEBCONTENT_BASE_DIR + File.separator + "resource" 
                + File.separator + "uploadimg" + File.separator + filePath;
        boolean fileDelete = FileUploader.delete(delFilePath);

        if (!fileDelete) {
            throw new Exception("消费打折记录[" + id + "]对应图片[" + filePath + "]删除失败");
        }

        return updateDao.delete("discount.deleteDiscount", id);
    }
    
    public int deleteManyDiscount(Integer[] ids) throws ClassCastException, SQLException {
        // 删除图片
        List<Object> delRs = deleteImgFiles(ids);
        return updateDao.batchDelete("discount.deleteDiscount", delRs);
    }
    
    /**
     * 批量删除图片
     * @param ids
     * @return
     * @throws ClassCastException
     * @throws SQLException
     * @create 2013-3-12 下午10:54:05
     */
    private List<Object> deleteImgFiles(Integer[] ids) throws ClassCastException, SQLException {
        List<Object> delRs = new ArrayList<Object>();
        for (Integer id : ids) {
            DiscountBean oldRecord = this.getDiscountDetail(id);
            String filePath = oldRecord.getSrcUrl();
            String delFilePath = ConfConst.WEBCONTENT_BASE_DIR + File.separator + "resource" 
                    + File.separator + "uploadimg" + File.separator + filePath;
            boolean fileDelete = FileUploader.delete(delFilePath);
            if (fileDelete) {
                log.debug("消费打折记录[" + id + "]对应图片[" + filePath + "]删除成功。");
                delRs.add(id);
            }
        }

        return delRs;
    }
    
    public void setQueryDao(IQueryDao queryDao) {
        this.queryDao = queryDao;
    }

    public void setUpdateDao(IUpdateDao updateDao) {
        this.updateDao = updateDao;
    }
    
}
